package cn.engage.basic.service.impl;


import cn.engage.basic.config.BussinessException;
import cn.engage.basic.constant.BaseConstant;
import cn.engage.basic.dto.MailRegisterDto;
import cn.engage.basic.dto.PhoneRegisterDto;
import cn.engage.basic.service.RegisterService;
import cn.engage.basic.util.MD5Utils;
import cn.engage.basic.util.StrUtils;
import cn.engage.user.domain.Logininfo;
import cn.engage.user.domain.User;
import cn.engage.user.mapper.LogininfoMapper;
import cn.engage.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 注册业务
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    // 手机号注册保存到数据库
    @Override
    public void phoneRegister(PhoneRegisterDto dto) {
        // 验证参数
        this.verifyParam(dto);
        // 插 先插logininfo 再插user
        User user = dtoConvertUser(dto);
        Logininfo logininfo = userConvertLogininfo(user);
        // 添加注册用户到logininfo
        logininfoMapper.add(logininfo);
        // 添加注册用户到user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }
    // 邮箱注册保存到数据库
    @Override
    public void MailRegister(MailRegisterDto dto) {
        // 验证码是否正确
        String eCode = (String) redisTemplate.opsForValue().get(dto.getMail());
        if (StringUtils.isBlank(eCode) || eCode.equals(dto.getMailCode())){
            throw new BussinessException("验证码输入错误");
        }
        // 两次密码是否一致
        if (!dto.getPassword().equals(dto.getPasswordRepeat())) {
            throw new BussinessException("两次密码不一致！");
        }
        // 是否注册过
        Logininfo byEmail = logininfoMapper.getByEmail(dto.getMail());
        if (byEmail != null){
            throw new BussinessException("该邮箱已注册！");
        }
        // 添加到logininfo和user表中

        /* 对密码进行加密*/
        // 获取盐值
        String randomString = StrUtils.getComplexRandomString(32);
        // 盐值加密码
        String NewPassword = randomString + dto.getPassword();
        // 用MD5对密码进行加密
        String MD5Password = MD5Utils.encrypByMd5(NewPassword);
        // 给user赋值相当于get set方法
        User user = User.builder().username(dto.getMail())
                .email(dto.getMail())
                .salt(randomString)
                .password(MD5Password)
                .state(1)
                .createtime(new Date())
                .build();
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    // 复制user的字段内容赋值给logininfo
    private Logininfo userConvertLogininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        return logininfo;
    }

    private User dtoConvertUser(PhoneRegisterDto dto) {
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 盐值 + 密码
        String password = salt + dto.getPassword();
        // 通过MD5对密码进行加密
        String encryPwd = MD5Utils.encrypByMd5(password);
        // builder相当于get方法
        return User
                .builder()
                .username(dto.getPhone())
                .phone(dto.getPhone())
                .salt(salt)
                .password(encryPwd)
                .state(1)
                .createtime(new Date())
                .build();

    }

    private void verifyParam(PhoneRegisterDto dto) {
        // 判断非空
        // 两次密码是否一致
        if (!dto.getPassword().equals(dto.getPasswordRepeat())) {
            throw new BussinessException("两次密码不一致！");
        }
        // 验证码是否正确 / 两次手机号是否一致
        String redisSmsCode = (String) redisTemplate.opsForValue().get(
                String.format(BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getPhone()));
        if (StringUtils.isBlank(redisSmsCode)) {
            throw new BussinessException("验证码错误！");
        }
        if (!redisSmsCode.equals(dto.getSmsCode())) {
            throw new BussinessException("验证码错误！");
        }
        // 是否注册过
        Logininfo byPhone = logininfoMapper.findByPhone(dto.getPhone());
        if (null != byPhone) {
            throw new BussinessException("该手机号已注册！");
        }
    }
}
